package com.wngbms.netty._11tcp_perfect.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<ServerMsgEntity> {

    int count;

    public MyServerHandler() {
        System.out.println(Thread.currentThread().getName() + " new MyServerHandler");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ServerMsgEntity msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("服务器接收到信息如下");
        System.out.println("长度=" + len);
        String s = new String(content, Charset.forName("utf-8"));
        System.out.println("内容=" + s);

        System.out.println("服务器接收到消息包数量=" + (++this.count));
        System.out.println();

        String responseContent = s + "-" + UUID.randomUUID().toString();
        int responseLen = responseContent.getBytes("utf-8").length;
        byte[] responseContent2 = responseContent.getBytes("utf-8");

        ServerMsgEntity serverMsgEntity = new ServerMsgEntity();
        serverMsgEntity.setLen(responseLen);
        serverMsgEntity.setContent(responseContent2);

        ctx.writeAndFlush(serverMsgEntity);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
